package com.example.manbook.service.impl;

import com.example.manbook.service.ResultService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class ResultServiceImpl implements ResultService {
    public List<String> execList(String cmd) throws IOException {
        // 创建ProcessBuilder对象
        ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);

        // 启动进程
        Process process = pb.start();

        // 获取进程的输入流
        InputStream inputStream = process.getInputStream();

        // 读取输入流数据并构建输出
        List<String> result = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            String line;
            while ((line = reader.readLine()) != null) {
                result.add(line);
            }
        }
        return result;
    }

    @Override
    public List<String> execInfo(String cmd, int num) throws IOException {
        String commandStr = "man " + num + " "+cmd;
        log.info("command = {}", commandStr);
        // 创建ProcessBuilder对象
        ProcessBuilder pb = new ProcessBuilder("bash", "-c", commandStr);
        // 启动进程
        Process process = pb.start();
        // 获取进程的输入流
        InputStream inputStream = process.getInputStream();
        // 读取输入流数据并构建输出
        List<String> result = new ArrayList<>();
        Pattern pattern = Pattern.compile("[a-zA-Z0-9\\._]+\\([0-9]+\\)");
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            String line;
            while ((line = reader.readLine()) != null) {
                Matcher matcher = pattern.matcher(line);
                String replacedStr = line;
                while(matcher.find()) {
                    String matchedStr = matcher.group();
                    System.out.println(matchedStr);
                    int index1 = matchedStr.indexOf('(');
                    int index2 = matchedStr.indexOf(')');
                    int n = Integer.parseInt(matchedStr.substring(index1+1, index2));
                    String cmdName = matchedStr.substring(0, index1);
                    replacedStr = replacedStr.replace(matchedStr, "<a href=\"/man/man"+n+"/"+cmdName+".html\">"+matchedStr+"</a>");
                }
                System.out.println(replacedStr);
                result.add(replacedStr);
            }
        }
        return result;
    }
}
